<?php

namespace app\purchase\logic;

use think\facade\Db;

class PurchaseLogic extends BasicLogic
{


    /**
     * @desc   获取采交货信息
     * @author luckyXiong
     * @date   2024-10-25
     */
    public function getPurchaseList($params=[]){
        $limit           = getIsset($params,'limit',10);
        $spu             = getIsset($params,'spu');
        $contract_number = getIsset($params,'contract_number');
        $supply_id       = getIsset($params,'supply_id');
        $purchase_time   = getIsset($params,'purchase_time');
        $arrival_status  = getIsset($params,'arrival_status');
        $delivery_status = getIsset($params,'delivery_status');
        $where           = [];

        if($spu){
            $where[] = ['spu', 'like', '%' . $spu . '%'];
        }

        if (!empty($purchase_time)) {
            $where[]  = ['purchase_time', '>=', date('Y-m-d H:i:s',strtotime($purchase_time[0]))];
            $where[]  = ['purchase_time', '<=', date('Y-m-d H:i:s',strtotime($purchase_time[1]) + 3600*24-1)];
        }

        if($contract_number){
            $where[] = ['contract_number', '=',$contract_number];
        }

        if($arrival_status){
            $where[] = ['arrival_status', '=',$arrival_status];
        }

        if($delivery_status){
            $where[] = ['delivery_status', '=',$delivery_status];
        }

        if($supply_id){
            $where[] = ['supply_id', '=',$supply_id];
        }


        $field = '*';
        $res   = Db::name('purchase_inventory')
            ->field($field)
            ->where($where)
            ->order('purchase_time desc')
            ->paginate($limit);
        $list = $res->items()?:[];

        foreach($list as $k=>$v){
            $list[$k]['attachment_images'] = $v['attachment_images'] ? json_decode($v['attachment_images'],true):'';
        }
        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc   获取入库记录
     * @author luckyXiong
     * @date   2025-01-11
     */
    public function get_store_record($params=[]){
        $limit              = getIsset($params,'limit',10);
        $in_number          = getIsset($params,'in_number');
        $purchase_number    = getIsset($params,'purchase_number');
        $create_time        = getIsset($params,'create_time');
        $where              = [];

        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        if($purchase_number){
            $where[] = ['purchase_number', '=',$purchase_number];
        }

        $where[] = ['purchase_number', '<>',''];

        if($in_number){
            $where[] = ['in_number', '=',$in_number];
        }

        $field = 'in_number,purchase_number,create_time';

        $res   = Db::name('warehouse_in_store')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $items = $res->items()?:[];
        $arr  =  [];
        foreach($items as $k=>$item){
            $arr[$k]['in_number']       = $item['in_number'];
            $arr[$k]['purchase_number'] = $item['purchase_number']??'';
            $arr[$k]['warehouse']       = '武汉江夏仓库';
            $arr[$k]['status']          = '全部入库';
            $arr[$k]['create_time']     = $item['create_time']??'';
            $arr[$k]['sku_list']        = self::get_sku_list($item['in_number']);
        }

        $data = [
            'list'   => $arr,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);



    }


    /**
     * @desc   获取签收记录
     * @author luckyXiong
     * @date   2025-01-11
     */
    public function in_store_log($params=[]){
        $limit              = getIsset($params,'limit',10);
        $purchase_number    = getIsset($params,'purchase_number');
        $create_time        = getIsset($params,'create_time');
        $where              = [];

        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        if($purchase_number){
            $where[] = ['purchase_number', '=',$purchase_number];
        }

        $res = Db::name('warehouse_in_store_record')
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);

        $items = $res->items()?:[];
        $operater_ids  = array_column($items,'operater_id');
        //批量获取创建人;
        $admin_users     = Db::name('system_admin')->field('id,username')->whereIn('id',$operater_ids)->select()->toArray();
        $admin_users_map = array_column($admin_users,null,'id');
        foreach($items as $k=>$item){
            $items[$k]['warehouse']       = '武汉江夏仓库';
            $admin_users_info          = $admin_users_map[$item['operater_id']]??'';
            $items[$k]['operater']      = $admin_users_info['username']??'';
        }

        $data = [
            'list'   => $items,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);


    }

    /**
     * @desc   获取采购变更单接口
     * @author luckyXiong
     * @date   2025-01-11
     */
    public function getPurchaseChange($params=[]){
        $limit              = getIsset($params,'limit',10);
        $operater_id        = getIsset($params,'operater_id');
        $purchase_number    = getIsset($params,'purchase_number');
        $create_time        = getIsset($params,'create_time');
        $where              = [];

        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        if($purchase_number){
            $where[] = ['purchase_number', '=',$purchase_number];
        }

        if($operater_id){
            $where[] = ['operater_id', '=',$operater_id];
        }

        $field = '*';

        $res   = Db::name('purchase_manual_change')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $items = $res->items()?:[];

        $arr   = [];
        foreach($items as $k=>$item){
            //获取原始采购信息;
            $purchase_info  = Db::name('purchase_manual')
                                          ->field('purchase_number,track_info,supply_id,operater_id')
                                          ->where(['purchase_number'=>$item['purchase_number']])
                                          ->find();
            $supply_name    = Db::name('supply')->where(['id'=>$purchase_info['supply_id']])->value('supply_name');
            $username       = Db::name('system_admin')->where('id',$purchase_info['operater_id'])->value('username');
            $arr[$k]['purchase_number'] = $item['purchase_number']??'';
            $arr[$k]['warehouse']       = '武汉江夏仓库';
            $arr[$k]['status']          = '已完成';
            $arr[$k]['supply_name']     = $supply_name ?:'';
            $arr[$k]['operater_id']     = $purchase_info['operater_id']??'';
            $arr[$k]['operater']        = $username??'';
            $arr[$k]['create_time']     = $item['create_time']??'';
            $arr[$k]['sku_list']        = $item['sku_json'] ? json_decode($item['sku_json'],true):'';
        }

        $data = [
            'list'   => $arr,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc   获取1688采购单地址
     * @author luckyXiong
     * @date   2025-02-08
     */
    public function get_1688_address($params=[]){
           $list = Db::name('1688_token')->field('id,account_1688,address')->select()->toArray();
           return  $this->jsonMessage(200,true,'获取成功',$list);
    }











    /**
     * @desc   获取sku信息
     * @author luckyXiong
     * @date   2025-01-11
     */
    private function get_sku_list($in_number){
            $field = 'in_number,seller_sku,in_stores_quantity,create_time';
            $info  = Db::name('warehouse_in_store_detail')
                ->field($field)
                ->where('in_number',$in_number)
                ->select()
                ->toArray();
            foreach($info as $k=>$v){
                $spu_info                = explode('-', $v['seller_sku']);
                $spu                     = $spu_info[0]??'';
                $info[$k]['spu']         = $spu;
            }
            $spus         = array_column($info,'spu');
            $products     = Db::name('product')->field('spu,product_images')->whereIn('spu',$spus)->select()->toArray();
            $products_map = array_column($products,null,'spu');
            $default_image = Config('Logisticskey.product_image_default');
            foreach($info as $k=>$v){
                $product_images                     = $products_map[$v['spu']]??[];
                $display_images                     = $product_images['product_images'] ? current(json_decode($product_images['product_images'])) : '';
                $info[$k]['image_url']              = $display_images ? $display_images : $default_image;
                $info[$k]['warehouse_position']     = '无货架位';
                $info[$k]['create_time']            = $v['create_time']??0;
                $info[$k]['arrive_quantity']        = $v['in_stores_quantity']??0;
                $info[$k]['check_quantity']         = $v['in_stores_quantity'].'/'.'0';
                $info[$k]['had_quantity']           = $v['in_stores_quantity'].'/'.'0';
            }
            return  $info;
    }


    /**
     * @desc    新增采交货信息
     * @author luckyXiong
     * @date   2024-10-27
     */
    public function addPurchaseList($params=[]){
        $admin_id           = getIsset($params,'admin_id');
        $purchase_code      = getIsset($params,'purchase_code');
        $contract_number    = getIsset($params,'contract_number');
        $supply_id          = getIsset($params,'supply_id');
        $spu                = getIsset($params,'spu');
        $product_name       = getIsset($params,'product_name');
        $dev_delivery_nums  = getIsset($params,'dev_delivery_nums');
        $real_delivery_nums = getIsset($params,'real_delivery_nums');
        $arrival_status     = getIsset($params,'arrival_status');
        $delivery_status    = getIsset($params,'delivery_status');
        $attachment_images  = getIsset($params,'attachment_images');
        $remark             = getIsset($params,'remark');
        $purchase_time      = getIsset($params,'purchase_time');
        $pre_delivery_time  = getIsset($params,'pre_delivery_time');
        $actual_delivery_time= getIsset($params,'actual_delivery_time');

        if(!$contract_number){
            return $this->jsonMessage(201,false,'合同编号不能为空',null);
        }

        if(!$supply_id){
            return $this->jsonMessage(201,false,'供应商不能为空',null);
        }

        if(!$spu){
            return $this->jsonMessage(201,false,'spu不能为空',null);
        }

        if(!$product_name){
            return $this->jsonMessage(201,false,'商品名称不能为空',null);
        }

        $supply_name     = Db::name('supply')->where(['id'=>$supply_id])->value('supply_name');
        $create_operator = Db::name('system_admin')->where(['id'=>$admin_id])->value('id');

        $insert_info = [
            'purchase_code'     =>$purchase_code,
            'contract_number'   =>$contract_number,
            'supply_id'         =>$supply_id,
            'supply_name'       =>$supply_name,
            'spu'               =>$spu,
            'product_name'      =>$product_name,
            'dev_delivery_nums' =>$dev_delivery_nums,
            'real_delivery_nums'=>$real_delivery_nums,
            'arrival_status'    =>$arrival_status,
            'delivery_status'   =>$delivery_status,
            'attachment_images' =>$attachment_images ? json_encode($attachment_images):'',
            'remark'            =>$remark,
            'purchase_time'      =>$purchase_time,
            'pre_delivery_time'  =>$pre_delivery_time,
            'actual_delivery_time'=>$actual_delivery_time,
            'create_time'         =>date("Y-m-d H:i:s", time()),
            'create_operator'     =>$create_operator,
         ];

        $exist_info =  Db::name('purchase_inventory')->where(['contract_number'=>$insert_info['contract_number'],'spu'=>$insert_info['spu']])->find();
        if($exist_info){
            Db::name('purchase_inventory')->where('id',$exist_info['id'])->update(
                [
                    'update_time'             =>date("Y-m-d H:i:s", time()),
                    'update_operator'         =>$create_operator,
                ]
            );
        }else{
            Db::name('purchase_inventory')->insert($insert_info);
        }
        return      $this->jsonMessage(200,true,'操作成功',null);
    }










    /**
     * @desc   获取到货状态
     * @author luckyXiong
     * @date   2024-10-26
     */
    public function getArrivalStatus(){
        $info = Config('Logisticskey.arrival_status');
        $info = getLevel($info);
        $arr  = [];
        foreach($info as $v){
            $arr[] = [
                'id'             => $v['key'],
                'arrival_status' => $v['value'],
            ];
        }
        return json(DefaultResponse(200, true, '获取成功', $arr));
    }


    /**
     * @desc   获取交货进度
     * @author luckyXiong
     * @date   2024-10-26
     */
    public function getDeliveryStatus(){
        $info = Config('Logisticskey.delivery_status');
        $info = getLevel($info);
        $arr  = [];
        foreach($info as $v){
            $arr[] = [
                'id'                   => $v['key'],
                'delivery_status'      => $v['value'],
            ];
        }
        return json(DefaultResponse(200, true, '获取成功', $arr));
    }





}